﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using System.IO;
using System.Web.UI;
using System.Threading;
using System.Security.Cryptography;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Net;
using System.Xml.Linq;

namespace Qianwei.Common
{
    /// <summary>
    /// added by Martin 2011-1-15
    /// </summary>
    public partial class Util
    {
        #region 转换用户字输入的字符串为可正确显示的html

        /// <summary>
        /// 转换&为&amp;
        ///  空格为&nbsp;
        ///     <为&lt;
        ///     >为&gt;
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string ConvertToHtmlString(string source)
        {
            return source.Replace("&", "&amp;")
                .Replace(" ", "&nbsp;")
                .Replace("<", "&lt;")
                .Replace(">", "&gt;")
                .Replace("\r\n", "&nbsp;")
                .Replace("\n", "&nbsp;");
        }

        public static string ParseHtmlString(string source)
        {
            return source.Replace("&amp;", "&")
                .Replace("&nbsp;", " ")
                .Replace("&lt;", "<")
                .Replace("&gt;", ">")
                .Replace("&nbsp;", "\r\n")
                .Replace("&nbsp;", "\n")
                .Replace("&mdash;", "—");
        }
        #endregion

        #region 字符类型判断
        public static bool IsDecimail(string input)
        {
            if (input.Length == 0)
                return false;
            else
                return Regex.IsMatch(input, @"^[1-9]\d*\.\d*|0\.\d*[1-9]\d*|[1-9]\d*$");
        }
        public static bool IsInteger(string input)
        {
            if (input.Length == 0)
                return false;
            else
                return Regex.IsMatch(input, @"^[1-9]\d*$");
        }
        public static bool IsLoginName(string input)
        {
            if (input.Length == 0)
                return false;
            else
                return Regex.IsMatch(input, @"\w+([-.]\w+)*");
        }
        public static bool IsEmail(string input)
        {
            if (input.Length == 0)
                return false;
            else
                return Regex.IsMatch(input, @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        }
        #endregion

        #region 字符串处理
        //对于输入是字符类型的检查
		public static string GetParamString(object obj)
		{
			if(obj == null || obj.ToString() == string.Empty) return "";
			
			string objString = "";
			objString	= obj.ToString().Replace("'","");
			objString = objString.Replace("--","");

			objString = System.Web.HttpUtility.HtmlEncode(objString);
			//objString = objString.Replace(" ",""); //过滤参数中的空格
			return objString;
		}

        public static string DelSQLStr(string str)
        {
            if (str == null || str == "")
                return "";
            str = str.Replace(";", "");
            str = str.Replace("'", "");
            str = str.Replace("&", "");
            str = str.Replace("%20", "");
            str = str.Replace("--", "");
            str = str.Replace("==", "");
            str = str.Replace("<", "");
            str = str.Replace(">", "");
            str = str.Replace("%", "");
            str = str.Replace("+", "");
            str = str.Replace("-", "");
            str = str.Replace("=", "");
            str = str.Replace(",", "");
            return str;
        }

        public static int Len(string str)
        {
            System.Text.ASCIIEncoding n = new System.Text.ASCIIEncoding();

            byte[] b = n.GetBytes(str);
            int length = 0;
            for (int i = 0; i <= b.Length - 1; i++)
            {
                if (b[i] == 63)
                {
                    length++;
                }
                length++;
            }
            return length;
        }

        public static string SubString(string stringToSub, int length)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Singleline);
            char[] stringChar = stringToSub.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;

            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 3;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

                if (nLength > length)
                    break;
            }

            return sb.ToString();
        }

        //截取部分内容方法
        public static string SubStringContainHtml(string value, int length)
        {
            if (value.Length > length)
            {
                value = value.Substring(0, length);
                value = value + "...";
                return NoHTML(value);
            }
            else
            {
                return NoHTML(value);
            }
        }

        #region 回车,空格过滤
        /**/
        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="NoHTML">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "",
            RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", " ",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9",
            RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "",
            RegexOptions.IgnoreCase);

            Htmlstring.Replace("<", "");
            Htmlstring.Replace(">", "");
            Htmlstring.Replace("\r\n", "");
            Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();

            return Htmlstring;
        }
        #endregion
        #endregion

        #region SQL

        public static string ToSqlString(object value)
        {
            return " '" + value + "'";
        }

        public static string ToSqlLikeString(object value)
        {
            return " LIKE '%" + value.ToString().ToUpper() + "%' ";
        }

        public static string ToSqlInString(object value)
        {
            return " IN (" + value + ")";
        }

        #endregion

        public static string GetIP()
        {
            try
            {
                string ip = string.Empty;

                if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARD_FOR"].ToString();
                else
                    ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
                return ip;
            }
            catch
            {
                return "unknown ip";
            }
        }

        #region Export

        /// <summary>
        /// 把服务器端控件里的内容导出为WORD文档
        /// </summary>
        /// <param name="source"></param>
        /// <param name="filename"></param>
        public static void ExportWord(System.Web.UI.Control source, string filename)
        {
            //设置Http的头信息,编码格式
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".doc", System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentType = "application/ms-word";

            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            //关闭控件的视图状态
            source.Page.EnableViewState = false;

            //初始化HtmlWriter
            System.IO.StringWriter writer = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(writer);
            source.RenderControl(htmlWriter);

            //输出
            HttpContext.Current.Response.Write(writer.ToString().Replace("<link href=\"../App_Themes/Default/global.css\" type=\"text/css\" rel=\"stylesheet\" />", ""));
            HttpContext.Current.Response.End();
        }

        public static void ExportExcel(string temfile, object[] data, string outfilename)
        {
            bool isfile = false;
            string filepath = temfile;
            try
            {
                if (System.IO.File.Exists(temfile))
                {
                    isfile = true;
                    filepath = temfile;
                }
                else if (System.IO.File.Exists(HttpContext.Current.Server.MapPath("~") + "\\" + temfile))
                {
                    isfile = true;
                    filepath = HttpContext.Current.Server.MapPath("~") + "\\" + temfile;
                }
            }
            catch { }

            if (isfile)
            {
                string temstring = System.IO.File.ReadAllText(filepath);
                ExportExcel(temstring, data.ToList(), !isfile, outfilename);
            }
        }

        public static void ExportExcel(string temstring, List<object> data, bool usertemstring, string outfilename)
        {
            outfilename = string.IsNullOrEmpty(outfilename) ? ("file" + DateTime.Now.ToString("yyyyMMdd_HHmmss")) : outfilename;

            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer = true;
            HttpContext.Current.Response.Charset = "UTF8";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(outfilename + ".xls", System.Text.Encoding.UTF8));
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/ms-excel";

            string datastr = "";
            if (!usertemstring)
            {
                datastr = temstring;
            }
            else
            {
                datastr = @"
                        <!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">

                        <html xmlns=""http://www.w3.org/1999/xhtml"">
                        <head>
                            <title></title>
                            <meta http-equiv=""Content-Type"" content=""text/html; charset=UTF-8"" /> 
                            <style type=""text/css"">
                            {0}
                            </style>
                        </head>
                        <body>" + temstring + @"
                        </body>
                        </html>
                        ";
            }

            data.Insert(0, @"
                        table th
                        {border:1px #000000 solid;font-weight:bold;text-align:center;}
                        table td
                        {text-align:center;}
                        td{border:1px #000000 solid; text-align:center;width:160px;font-family:宋体,Verdana;}");

            HttpContext.Current.Response.Write(string.Format(datastr, data.ToArray()));
            HttpContext.Current.Response.End();
        }

        public static void ExportExcel(string temstring, List<object> data, bool usertemstring)
        {
            ExportExcel(temstring, data, usertemstring, null);
        }

        public static void ExportExcel(string temfile, object[] data)
        {
            ExportExcel(temfile, data, null);
        }

        /// <summary>
        /// GridVIew 导出 Excel                          
        /// </summary>
        public static void ExportExcel(GridView gv, string fileName)
        {
            HttpContext.Current.Response.Charset = "UTF-8";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
            HttpContext.Current.Response.ContentType = "application/ms-excel";
            HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(fileName) + ".xls");
            gv.Page.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            gv.RenderControl(hw);
            HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=UTF-8>");
            HttpContext.Current.Response.Write(tw.ToString());
            HttpContext.Current.Response.End();
        }

        #endregion
        

        #region JsonHelper

        /// <summary>         
        /// 序列化为JSON对象         
        /// </summary>   
        public static string JSONSerialize<T>(T obj)
        {
            return new JavaScriptSerializer().Serialize(obj);            
        }

        /// <summary>       
        /// JSON对象反序列化          
        /// </summary>
        public static T JSONDeserialize<T>(string data)
        {
            return new JavaScriptSerializer().Deserialize<T>(data);
        }

        #endregion

        #region 加密/解密

        /// <summary>
        /// 将密码加密成32位的md5字符串;
        /// </summary>
        /// <param name="Pwd">要加密的密码字符串</param>
        /// <returns>返回一个32位的md5字符串</returns>
        public static string MD5Encrypt(string Pwd)
        {
            MD5CryptoServiceProvider MD5Provider = new MD5CryptoServiceProvider();
            byte[] MD5Byte = MD5Provider.ComputeHash(Encoding.UTF32.GetBytes(Pwd));
            MD5Byte = MD5Provider.ComputeHash(MD5Byte);
            MD5Byte = MD5Provider.ComputeHash(MD5Byte);
            return BitConverter.ToString(MD5Byte).Replace("-", "");
        }

        /// <summary>
        /// DES加密
        /// </summary>
        public static string DESEncrypt(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
                ret.AppendFormat("{0:X2}", b);
            ret.ToString();
            return ret.ToString();
        }

        /// <summary>
        /// DES解密
        /// </summary>
        public static string DESDecrypt(string pToDecrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();

            StringBuilder ret = new StringBuilder();

            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }

        #endregion


        #region 客户端提示
        /// <summary>
        /// 提示信息然后转到指定url
        /// </summary>
        /// <param name="message"></param>
        /// <param name="url"></param>
        public static void PageAlertAndRedirectTo(string message, string url)
        {
            ScriptManager.RegisterStartupScript(HttpContext.Current.Handler as Control, typeof(Control), "alert", String.Format("alert('{0}');window.location='{1}';", message, url), true);
        }

        public static void PageAlert(string message)
        {
            ScriptManager.RegisterStartupScript(HttpContext.Current.Handler as Control, typeof(Control), "console", String.Format("alert('{0}');", message), true);
        }
        #endregion

        #region 业务操作
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <returns></returns>
        public static string GetCheckCode()
        {
            string checkCode = HttpContext.Current.Session["CheckCode"] == null ? "" : HttpContext.Current.Session["CheckCode"].ToString();
            return checkCode;
        }

        /// <summary>
        /// 当前登录用户
        /// </summary>
        public static object GetCurrentUser()
        {
            return HttpContext.Current.Session["UserInfo"];
        }

        /// <summary>
        /// 删除用户Session
        /// </summary>
        public static void ClearUserInfo()
        {
            if (HttpContext.Current.Session["UserInfo"] != null)
            {
                HttpContext.Current.Session.Remove("UserInfo");
            }
        }

        /// <summary>
        /// 设置当前用户
        /// </summary>
        /// <param name="user"></param>
        public static void SetUserInfo(object user)
        {
            HttpContext.Current.Session["UserInfo"] = user;
        }

        /// <summary>
        /// 删除验证码
        /// </summary>
        public static void ClearCheckCode()
        {
            if (HttpContext.Current.Session["CheckCode"] != null)
            {
                HttpContext.Current.Session.Remove("CheckCode");
            }
        }
        #endregion

    }
}
